// pages/home/home.js
const app = getApp()

Page({
  data: {
    userInfo: null,
    loading: false
  },

  onLoad() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  handleLogout() {
    this.setData({ loading: true });
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: `${app.globalData.baseUrl}/auth/logout`,
      method: 'POST',
      header: {
        'Authorization': token
      },
      success: (res) => {
        this.setData({ loading: false });
        if (res.data.code === 200) {
          wx.removeStorageSync('token');
          app.globalData.userInfo = null;
          wx.redirectTo({
            url: '/pages/login/login'
          });
        } else {
          wx.showToast({
            title: '退出失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
});
